<template>
  <div>
    <!--设为离职-->
    <el-dialog
      title="设为离职"
      :visible.sync="dimissionDialogVisible"
      width="640px"
      :before-close="handleDimissionClose"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="oneColumnDialog"
    >
      <el-form
        :model="dimissionFormData"
        ref="dimissionFormRef"
        :rules="dimissionRules"
        label-width="120px"
      >
        <el-form-item label="人员姓名：">
          <div>{{ this.employeeInfo.name }}</div>
        </el-form-item>
        <el-form-item label="离职日期：" prop="overDate">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="dimissionFormData.overDate"
            value-format="yyyy-MM-dd"
            class="form-item"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="离职原因：" prop="reason">
          <el-input
            type="textarea"
            rows="3"
            placeholder="请输入离职原因"
            v-model.trim="dimissionFormData.reason"
            class="mWidth"
          ></el-input>
        </el-form-item>
        <!-- 仅普洱显示 -->
        <div style="margin-left: 50px" v-if="isPuErUser()">
          <el-link style="line-height: 16px" type="primary" @click="download()"
            >点击下载《普洱市建设领域用人单位解除（终止）劳动合同证明书（样本）》
          </el-link>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dimissionDialogVisible = false" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="onDimission"
          :loading="isSaveLoading"
          class="save"
          >保 存</el-button
        >
      </span>
    </el-dialog>

    <!--设为在职-->
    <el-dialog
      title="设为在职"
      :visible.sync="jobDialogVisible"
      width="900px"
      :before-close="handleJobClose"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        :model="jobFormData"
        ref="jobFormRef"
        :rules="jobRules"
        label-width="120px"
        style="padding-top: 8px"
      >
        <el-row>
          <el-col :span="12" class="col-position">
            <el-form-item label="人员姓名：">
              <div>{{ this.employeeInfo.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="所属参建单位：" prop="companyName">
              <el-select
                v-model="jobFormData.companyName"
                placeholder="请选择参建单位"
                @change="handleChange"
                class="form-item"
                clearable
              >
                <!-- <el-option v-for="item in partUnitsOptions" :key="item.code " :label="item.name" :value="item.name"></el-option> -->
                <el-option
                  v-for="item in partUnitsOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="人员类型：" prop="type">
              <el-select
                v-model="jobFormData.type"
                placeholder="请选择人员类型"
                class="form-item"
                clearable
              >
                <el-option
                  v-for="item in employeeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="选择班组：" prop="groupId">
              <el-select
                v-model="jobFormData.groupId"
                placeholder="请选择班组"
                class="form-item"
                @change="changeLocationValue"
                clearable
              >
                <el-option
                  v-for="item in groupIdOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="工种：" prop="workType">
              <el-select
                v-model="jobFormData.workType"
                placeholder="请选择工种"
                class="form-item"
                clearable
              >
                <el-option
                  v-for="item in workTypeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="雇佣开始日期：" prop="startDate">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="jobFormData.startDate"
                value-format="yyyy-MM-dd"
                class="form-item"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="雇佣结束日期：" prop="endDate">
              <el-date-picker
                v-model="jobFormData.endDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                class="form-item"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="工资卡银行：" prop="bankId">
              <el-select
                v-model="jobFormData.bankId"
                placeholder="请选择工资卡银行"
                class="form-item"
                clearable
              >
                <el-option
                  v-for="item in bankOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="银行卡号：" prop="account">
              <el-input
                v-model="jobFormData.account"
                class="form-item"
                placeholder="请输入银行卡号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="考勤卡：" prop="attNo">
              <el-input
                v-model="jobFormData.attNo"
                class="form-item"
                placeholder="请输入考勤卡号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="计量单位：" prop="unit">
              <!--        <el-input v-model="jobFormData.unit" class="form-item"></el-input>-->
              <el-select
                class="form-item"
                v-model="jobFormData.unit"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in unitOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-position">
            <el-form-item label="计量单价：" prop="price">
              <el-input
                v-model="jobFormData.price"
                class="form-item"
                placeholder="请输入计量单价"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="jobDialogVisible = false" class="cancel"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="onJob"
          :loading="isSaveLoading"
          class="save"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'empOverDate',
  data() {
    var validateReason = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('离职原因不能为空'))
      } else {
        if (value.length <= 0) {
          callback(new Error('离职原因不能为空'))
        } else {
          callback()
        }
      }
    }
    return {
      employeeInfo: {},
      dimissionDialogVisible: false, //离职dialog
      jobDialogVisible: false, //在职dialog
      isSaveLoading: false, // 保存loading
      bankOptions: [], //银行选择
      employeeOptions: [], //人员类型选择
      workTypeOptions: [], //工种类型选择
      partUnitsOptions: [], //参建单位选择
      unitOptions: [], //计量单位
      dimissionFormData: {
        overDate: '',
        reason: '',
      },
      dimissionRules: {
        overDate: [
          {
            required: true,
            message: '请输入离职时间',
            trigger: 'blur',
          },
        ],
        reason: [
          {
            required: true,
            validator: validateReason,
            trigger: 'blur',
          },
        ],
      },
      jobFormData: {
        projectId: '',
        uscc: '',
        groupId: '',
        companyName: '',
        groupName: '',
        employeeId: '',
        type: '',
        workType: '',
        bankId: '',
        account: '',
        attNo: '',
        startDate: '',
        endDate: '',
        unit: '',
        price: '',
      },
      jobRules: {
        companyName: [
          {
            required: true,
            message: '请选择参建单位名称',
            trigger: 'change',
          },
        ],
        account: [
          {
            // required: true,
            pattern: /^\d{15,19}$/,
            message: '请输入15-19 位纯数字的银行卡号',
            trigger: 'blur',
          },
        ],
        type: [
          { required: true, message: '请选择人员类型', trigger: 'change' },
        ],
        groupId: [{ required: true, message: '请选择班组', trigger: 'change' }],
        workType: [
          { required: true, message: '请选择工种', trigger: 'change' },
        ],
        startDate: [
          { required: true, message: '请选择雇佣开始时间', trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '请选择雇佣结束时间', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    this.getDicitemType('EMPLOYEE_TYPE') //人员类型
    this.getDicitemType('WORKER_TYPE') //工种
    this.getDicitemType('BANK_TYPE') //银行类型
    this.getDicitemType('UNIT') //银行类型
    this.$store.commit('SET_INFO', ['groupIdOptions', []])
  },
  computed: {
    ...mapState(['groupIdOptions']),
  },
  methods: {
    ...mapActions(['getGroupList']),
    refreshData() {
      this.$emit('refresh-data')
    },
    restFiled(fromRef) {
      this.$nextTick(() => {
        this.$refs[fromRef].resetFields()
      })
    },
    setOutWork(index, row) {
      this.employeeInfo = row
      this.dimissionFormData.overDate = ''
      this.dimissionFormData.reason = ''
      this.dimissionDialogVisible = true
      this.restFiled('dimissionFormRef')
    },
    setJobWork(index, row) {
      this.employeeInfo = row
      this.jobFormData.projectId = row.projectId
      this.jobFormData.uscc = row.uscc
      this.jobFormData.groupId = row.groupId
      this.jobFormData.companyName = row.companyName
      this.jobFormData.groupName = row.groupName
      this.jobFormData.employeeId = row.employeeId
      this.jobFormData.type = row.type
      this.jobFormData.workType = row.workType
      this.jobFormData.bankId = row.bankId
      this.jobFormData.account = row.account
      this.jobFormData.attNo = row.attNo
      this.jobFormData.startDate = row.startDate
      this.jobFormData.endDate = row.endDate
      this.jobFormData.unit = row.unit
      this.jobFormData.price = row.price
      this.getGroupList({ projectId: row.projectId, uscc: row.uscc })

      this.getPartUnitsData(row.projectId)
      this.jobDialogVisible = true
      // this.restFiled("jobFormRef");
    },
    handleDimissionClose() {
      this.dimissionDialogVisible = false
    },
    handleJobClose() {
      this.jobDialogVisible = false
    },
    onDimission() {
      this.$refs.dimissionFormRef.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveLoading = true
          this.submitFormDimission()
        } else {
          return false
        }
      })
    },
    submitFormDimission() {
      var data = {
        id: this.employeeInfo.id,
        overDate: this.dimissionFormData.overDate,
        reason: this.dimissionFormData.reason,
      }
      this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/outgoing',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.refreshData()
            this.$message({
              message: '设置离职成功',
              type: 'success',
            })
            this.removechildalert(
              this.employeeInfo.projectId,
              this.employeeInfo.idcard,
              this.employeeInfo.name
            )
            this.handleDimissionClose()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('设置离职失败')
          this.isSaveLoading = false
        })
    },
    onJob() {
      this.$refs.jobFormRef.validate((valid) => {
        if (valid) {
          var birthYear = this.employeeInfo.idcard.substring(6, 10)
          var birthMonth = this.employeeInfo.idcard.substring(10, 12)
          var birthDay = this.employeeInfo.idcard.substring(12, 14)
          var isAdult = this.isChildWorker(birthYear, birthMonth, birthDay)
          //15位身份证不存在童工，不需验证
          if (
            this.employeeInfo.idcard.length == 18 &&
            isAdult > 0 &&
            this.jobFormData.type == '70'
          ) {
            //童工，班组长
            this.showTipChild()
          } else if (
            this.employeeInfo.idcard.length == 18 &&
            isAdult > 0 &&
            this.jobFormData.type != '70'
          ) {
            //童工，非班组长
            this.showTipChildTwo()
          } else if (isAdult == 0 && this.jobFormData.type == '70') {
            //非童工，班组长
            this.replaceGroup()
          } else {
            //非童工，非班组长
            this.isSaveLoading = true
            this.submitFormJob()
          }
          // 保存更新
          // this.isSaveLoading = true;
          // this.submitFormJob();
          //   this.replaceGroup();
        } else {
          return false
        }
      })
    },
    replaceGroup() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/findgroupleader',
        data: {
          projectId: this.jobFormData.projectId,
          uscc: this.jobFormData.uscc,
          groupId: this.jobFormData.groupId,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              //1.存在班组长  2.当前选择班组长 就弹框提示
              if (
                response.data.result.name &&
                this.jobFormData.type == '70' &&
                this.employeeInfo.idcard != response.data.result.idCard
              ) {
                this.showTip(response.data.result.name)
              } else {
                this.isSaveLoading = true
                this.submitFormJob()
              }
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    showTip(oldGroup) {
      var html =
        '<div>该班组已设置班组长' +
        oldGroup +
        ',是否替换为' +
        this.employeeInfo.name +
        '？替换后' +
        oldGroup +
        '将自动离职' +
        '</div>'
      this.$confirm(html, '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then((action) => {
          this.isSaveLoading = true
          this.submitFormJob()
        })
        .catch(() => {})
    },
    submitFormJob() {
      var data = {
        projectId: this.jobFormData.projectId,
        uscc: this.jobFormData.uscc,
        groupId: this.jobFormData.groupId,
        companyName: this.jobFormData.companyName,
        groupName: this.jobFormData.groupName,
        employeeId: this.jobFormData.employeeId,
        type: this.jobFormData.type,
        workType: this.jobFormData.workType,
        bankId: this.jobFormData.bankId,
        account: this.jobFormData.account,
        attNo: this.jobFormData.attNo,
        startDate: this.jobFormData.startDate,
        endDate: this.jobFormData.endDate,
        unit: this.jobFormData.unit,
        price: this.jobFormData.price,
      }
      this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/onjob',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.refreshData()
            this.$message({
              message: '设置在职成功',
              type: 'success',
            })
            this.handleJobClose()
            // this.addchildalert(
            // //   this.jobFormData.projectId,
            // //   this.jobFormData.idcard,
            // //   this.jobFormData.name
            //     this.employeeInfo.projectId,
            //      this.employeeInfo.idcard,
            //     this.employeeInfo.name
            // );
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('设置在职失败')
          this.isSaveLoading = false
        })
    },
    getPartUnitsData(projectId) {
      this.axios({
        method: 'post',
        url: 'api-p/projectcompany/expand/findbyprojectid',
        data: {
          projectId: projectId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.partUnitsOptions = response.data.result
          }
        })
        .catch((response) => {})
    },
    handleChange(value) {
      // var uscc = this.jobFormData.uscc;
      this.jobFormData.uscc = value
      if (!this.jobFormData.uscc) {
        this.jobFormData.groupId = ''
        this.$store.commit('SET_INFO', ['groupIdOptions', []])
      } else {
        this.getGroupList({
          projectId: this.jobFormData.projectId,
          uscc: this.jobFormData.uscc,
        })
        this.jobFormData.groupId = ''
      }
    },
    changeLocationValue(val) {
      let obj = {}
      obj = this.groupIdOptions.find((item) => {
        return item.code === val
      })
      this.jobFormData.groupName = obj.name
    },
    getDicitemType(dicitemType) {
      this.axios({
        method: 'post',
        url: 'api-bs/base/dicitem/findbytype',
        data: {
          type: dicitemType,
        },
      })
        .then((response) => {
          if (dicitemType == 'EMPLOYEE_TYPE') {
            //人员类型
            this.employeeOptions = response.data.result
          } else if (dicitemType == 'WORKER_TYPE') {
            //工种
            this.workTypeOptions = response.data.result
          } else if (dicitemType == 'BANK_TYPE') {
            //银行类型
            this.bankOptions = response.data.result
          } else if (dicitemType == 'UNIT') {
            this.unitOptions = response.data.result
          }
        })
        .catch((response) => {})
    },
    /**
     * 消除童工预警接口
     * 此接口仅用于人员离职消除童工预警
     * @param projectId 项目id
     * @param idCard 员工身份证号码
     * @param name 员工姓名
     */
    removechildalert(projectId, idCard, name) {
      this.axios({
        method: 'post',
        url: 'api-a/cs/alert/base/removechildalert',
        data: {
          projectId: projectId,
          idCard: idCard,
          name: name,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            // this.$message({
            //   message: "设置在职成功",
            //   type: "success"
            // });
          } else {
            // this.$message({
            //   type: "error",
            //   message: response.data.errorMsg
            // });
            // this.isSaveLoading = false;
          }
        })
        .catch((error) => {
          // this.$message.error("设置在职失败");
          // this.isSaveLoading = false;
        })
    },
    // 入职时调用
    addchildalert(projectId, idCard, name) {
      this.axios({
        method: 'post',
        url: 'api-a/cs/alert/base/addchildalert',
        data: {
          projectId: projectId,
          idCard: idCard,
          name: name,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
          } else {
          }
        })
        .catch((error) => {})
    },
    //童工且为班组长
    showTipChild(typeName) {
      this.$confirm('此人为童工,您确定添加吗？', '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then((action) => {
          this.replaceGroup()
        })
        .catch(() => {})
    },
    //童工非班组长
    showTipChildTwo(typeName) {
      this.$confirm('此人为童工,您确定添加吗？', '提示', {
        dangerouslyUseHTMLString: true,
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then((action) => {
          this.submitFormJob()
        })
        .catch(() => {})
    },
    download() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/findUrl',
        data: {
          name: 'empDismissed',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            window.open(response.data.result.url)
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {})
    },
  },
}
</script>

<style scoped>
.form-item {
  width: 300px !important;
}
</style>
